#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "NoCopy.hpp"
#include "InetAddr.hpp"

static int gport=8884;
static int gsocketd=-1;
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};
using namespace log_ns;
class serve{
    public:
    serve(int port=gport)
    :_socketd(gsocketd),
     _port(port),
     isrunning(0)
    {  
    }
    void Init_Socket(){
        _socketd = socket(AF_INET, SOCK_DGRAM, 0);
    if (_socketd < 0) {
        LOG(FATAL, "socket error\n");
        exit(SOCKET_ERROR);
    } else {
        LOG(DEBUG, "socket create success, _socketd: %d\n", _socketd);
    }
   
    // 将 sockaddr_in local 的定义移动到正确的作用域
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(_port);
    local.sin_addr.s_addr = INADDR_ANY;
 
    int n = bind(_socketd, (struct sockaddr*)&local, sizeof(local));
    if (n < 0) {
        LOG(FATAL, "bind error\n");
        exit(BIND_ERROR);
    }
    LOG(DEBUG, "socket bind success\n");
    }
     void to_start(){
        isrunning=1;
        char buff[1024];
        struct sockaddr_in sou;
        socklen_t len=sizeof(sou);
        while(1){
            ssize_t m = recvfrom(_socketd,buff,sizeof(buff)-1,0,(sockaddr *)&sou,&len);
            if(m>0){
            std::string s_mes("server accept :");
            buff[m]=0;
            InetAddr a(sou);
            std::cout << a.Ip()<< a.Port()<< buff<<std::endl;
            //s_mes=s_mes+buff;
            std::cout << s_mes<< std::endl;
            sendto(_socketd,s_mes.c_str(),s_mes.size(),0,(struct sockaddr *)&sou, len);
            }
            /*
             ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                inbuffer[n] = 0;
                std::cout << "[" << addr.Ip() << ":" << addr.Port() << "]# " << inbuffer << std::endl;


                std::string echo_string = "[udp_server echo] #";
                echo_string += inbuffer;
                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr *)&peer, len);
            }
            else
            {
                std::cout << "recvfrom ,  error"  << std::endl;
            }
        }
            */

        }
        
        while(1);
    }
    ~serve()
    {
         if(_socketd > gsocketd) ::close(_socketd);
    }
    private:
    int _socketd;
    int _port;
    int isrunning;
};